#!/bin/sh
pidfile=/tmp/tspprofiler.lock
action="$1"

# Load the rc.status script for this service.
. /etc/rc.status

case "$action" in
    start*)
        if [ -e $pidfile ]; then
                $0 status &>/dev/null
                ret=$?
                if [ $ret = 1 ]; then
                                echo "Warning: found stale pidfile (unclean shutdown?)"
                elif [ $ret = 0 ]; then
                                echo "tspprofiler is already running ($pidfile)"
                                rc_failed $ret
                                rc_status -v1
                                rc_exit
                fi
        fi

        echo -n "Starting tspprofiler "
        mono-service2 -l:$pidfile -n:ProfileSwappers @prefix@/lib/tspcluster/tspcluster.exe
        echo "."
        ;;

    stop)
        echo -n "Stopping tspprofiler "
        if ! [ -f $pidfile ]; then
                echo -n "(not running)"
        else
                pid=$(<$pidfile)
                kill -TERM $pid 2>/dev/null
                case $? in
                    1)  echo -n "(not running)";;
                    0)  # wait until the processes are gone (the parent is the last one)
                        echo -n "(waiting for all children to terminate) "
                        for ((wait=0; wait<120; wait++)); do
                                if test -f $pidfile; then
                                        usleep 500000
                                        continue
                                fi
                                if ! test -f /proc/$pid/exe; then
                                        break
                                fi

                        done
                        ;;
                esac
        fi

        rc_status -v
        ;;

    status)
        echo -n "Checking for tspprofiler: "
        # we don't use checkproc here since it is confused when we exchange the binaries
        if ! [ -f $pidfile ]; then
                # not running
                rc_failed 3
        elif [ -s $pidfile -a -d /proc/$(<$pidfile) ]; then
                # running
                :
        else
                # stale pid file
                rc_failed 1
                #rm -f $pidfile
        fi
        rc_status -v
        ;;

    *)
        
        echo "Usage: $0 <command>"
        echo ""
        echo "where <command> is one of:"
        echo "       start              - start tspprofiler service"
        echo "       stop               - stop tspprofiler service (sending SIGTERM to parent)"
        echo "       status             - get status information"
    exit 1
    ;;
esac